package spark.network;

import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Collection;

import spark.network.protocol.Base;
import spark.network.IPlayerListEventListener;
import spark.network.IConnections;
import spark.network.NetworkConnection;

public class ActiveClientList implements IPlayerListEventListener, IConnections {
	private static Logger logger = Logger.getLogger(ActiveClientList.class);

	private HashMap<Long, NetworkConnection> clients = new HashMap<Long, NetworkConnection>();
	private HashMap<Long, NetworkConnection> authorizedClients = new HashMap<Long, NetworkConnection>();

	@Override
	public boolean isValid(InetSocketAddress clientAddress, Base packet) {
		NetworkConnection client = clients.get(packet.getSession());
		//if the player sent the wrong session he is not a network player
		if(client == null) {
			return false;
		}
		//if the right session was sent but from a different address+port than is known to us don't
		//accept the client as a network player either
		return client.getAddress().equals(clientAddress);
	}

	@Override
	public NetworkConnection getConnection(long session) {
		return clients.get(session);
	}

	/**
	 * Adds the provided connection along with its matching network address to the list.
	 * If a client with this address already exists the old value is replaced with the new one.
	 * @param connection Connection object to add to the list.
	 */
	public void addConnection(NetworkConnection connection){
		clients.put(connection.getSession(), connection);
	}

	/**
	 * Up the status of the client with the provided session to authorized.
	 * @param session Sessio of a client which must be contained in the list.
	 */
	public void authorizeClient(long session) {
		authorizedClients.put(session, clients.get(session));
	}

	/**
	 * Take away authorized status from a client.
	 * @param session Sessio of a client which must be an authorized client.
	 */
	public void unauthorizeClient(long session) {
		authorizedClients.remove(session);
	}

	public Collection<NetworkConnection> getAuthorizedClients() {
		return authorizedClients.values();
	}

	@Override
	public void loggedIn(long session) {
		authorizeClient(session);
	}

	@Override
	public void loggedOut(long session) {
		unauthorizeClient(session);
		clients.remove(session);
	}
}
